import 'dart:io';
import 'dart:math';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:live_music/event/momonEvent.dart';
import 'package:live_music/models/tag_model.dart';
import 'package:live_music/pages/publish/index.dart';
import 'package:live_music/pages/publish/FeedDouYinPublishPage.dart';
import 'package:live_music/services/tagService.dart';
import 'package:live_music/utils/common.dart';
import 'package:live_music/utils/eventBusUtils.dart';
import 'package:live_music/utils/oss.dart';
import 'package:path_provider/path_provider.dart';

class DouYinPulish extends StatefulWidget {
  DouYinPulish({Key key}) : super(key: key);

  @override
  _DouYinPulishState createState() => _DouYinPulishState();
}

class _DouYinPulishState extends State<DouYinPulish>
    with SingleTickerProviderStateMixin {
  TextEditingController _userNameEditController;
  bool disabledPublish = true;
  @override
  void initState() {
    super.initState();
    _userNameEditController = TextEditingController();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: PreferredSize(
            preferredSize: Size.fromHeight(50),
            child: AppBar(
              elevation: 0.0,
              centerTitle: true,
              title: Center(
                child: Container(
                  alignment: Alignment.center,
                  child: Row(
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      GestureDetector(
                        child: Text(
                          "取消",
                          style: TextStyle(
                              fontSize: 16,
                              color: Colors.grey,
                              fontWeight: FontWeight.w500),
                        ),
                        onTap: () {
                          Get.back();
                        },
                      ),
                      Container(
                        child: Text(
                          "解析抖音链接",
                          style: TextStyle(
                              fontSize: 16,
                              color: Colors.black,
                              fontWeight: FontWeight.w500),
                        ),
                      ),
                      Container(
                          margin: EdgeInsets.symmetric(vertical: 15),
                          width: 60,
                          height: 30,
                          alignment: Alignment.center,
                          child: ElevatedButton(
                              style: ButtonStyle(
                                  shape: MaterialStateProperty.all(
                                      RoundedRectangleBorder(
                                          borderRadius:
                                              BorderRadius.circular(20))),
                                  backgroundColor: MaterialStateProperty.all(
                                    Colors.redAccent,
                                  )),
                              onPressed: disabledPublish ? _jiexi : null,
                              child: const Center(
                                child: Text(
                                  '解析',
                                  style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 12,
                                      fontWeight: FontWeight.w500),
                                ),
                              ))),
                    ],
                  ),
                ),
              ),
              automaticallyImplyLeading: false,
            )),
        body: Column(children: [_buildName()]));
  }

  static String getRandom(int num) {
    String alphabet = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
    String left = "";
    for (var i = 0; i < num; i++) {
//    right = right + (min + (Random().nextInt(max - min))).toString();
      left = left + alphabet[Random().nextInt(alphabet.length)];
    }
    return left;
  }

  Future _jiexi() async {
    EasyLoading.show(status: '解析中...');
    try {
      setState(() {
        disabledPublish = false;
      });
      Dio dio = Dio();
      dio.options.responseType = ResponseType.json;
      dio.options.headers = {
        'Connection': 'keep-alive',
        'sec-ch-ua':
            '" Not A;Brand";v="99", "Chromium";v="90", "Microsoft Edge";v="90"',
        'Accept': '*/*',
        'X-Requested-With': 'XMLHttpRequest',
        'sec-ch-ua-mobile': '?0',
        'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36 Edg/90.0.818.66',
        'Sec-Fetch-Site': 'same-origin',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Dest': 'empty',
        'Referer':
            'https://www.iesdouyin.com/share/video/6561991332561161476/?region=CN&mid=6561671254439365390&u_code=0&titleType=title&did=MS4wLjABAAAA2Cy8LTQsppRk4gci9RcF18kdcuNyaQRtZcZt0BGbylg&iid=MS4wLjABAAAAWHQavP6vURszBFMcxNrThBB0wrNEDWNzLdTKiuW5cI_cOJvn7h0u20Uz8R292pd2&with_sec_did=1&utm_source=copy_link&utm_campaign=client_share&utm_medium=android&app=aweme&scheme_type=1',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'Cookie':
            'MONITOR_WEB_ID=4843f090-b627-46db-bbe2-f757b4ea21a0; _tea_utm_cache_1243={%22utm_source%22:%22copy_link%22%2C%22utm_medium%22:%22android%22%2C%22utm_campaign%22:%22client_share%22}'
      };
      dynamic result = await dio.post("http://cgqhhxx.com:9999/go",
          data: {"name": _userNameEditController.text, "password": ""});
      Map<String, dynamic> responseData = result.data["data"];
      Directory storageDir = await getApplicationDocumentsDirectory();
      String storagePath = storageDir.path;
      String savePath = storagePath + "/" + getRandom(12) + ".jpg";
      File file = new File(savePath);
      var response = await dio.get(responseData['cover'],
          options: Options(responseType: ResponseType.bytes));
      print(file);
      await file.writeAsBytes(response.data, mode: FileMode.append);
      Map<String, dynamic> videoCoverInfo = {
        "coverHeight": "",
        "coverUrl": "",
        "coverWidth": "",
      };
      videoCoverInfo['coverUrl'] =
          await UploadOss.upload(file, rootDir: "moment/image");
      print(videoCoverInfo['coverUrl']);
      Image image = Image.file(file);
      image.image
          .resolve(ImageConfiguration())
          .addListener(ImageStreamListener((ImageInfo info, bool _) {
        videoCoverInfo['coverWidth'] = info.image.width;
        videoCoverInfo['coverHeight'] = info.image.height;
      }));

      var appDocDir = await getTemporaryDirectory();
      String savePath1 = appDocDir.path + "/temp.mp4";
      String fileUrl = responseData['video_url'];
      await dio.download(fileUrl, savePath1, onReceiveProgress: (count, total) {
        print((count / total * 100).toStringAsFixed(0) + "%");
      });
      File file1 = new File(savePath1);
      PublishFileMgs publishFileMgs = PublishFileMgs();

      publishFileMgs.size = _changeSize(await file1.length());
      publishFileMgs.name = "temp.mp4";
      publishFileMgs.path = file1.path;
      EasyLoading.dismiss(animation: true);
      Future.delayed(Duration(milliseconds: 1000), () {
        setState(() {
          disabledPublish = true;
        });
      });
      Get.off(FeedDouYinPublishPage(
          publishFileMgs: publishFileMgs,
          publishType: PublishType.video,
          videoCoverInfo: videoCoverInfo,
          contentText: responseData['desc'],
          videoSourceUrl: responseData['video_url'],
          videoText: responseData['video_text']));
    } catch (e) {
      EasyLoading.showError('解析失败');
      EasyLoading.dismiss(animation: true);
      Future.delayed(Duration(milliseconds: 1000), () {
        setState(() {
          disabledPublish = true;
        });
      });
    }
  }

  _changeSize(limit) {
    String size = "";
    //内存转换
    if (limit < 0.1 * 1024) {
      //小于0.1KB，则转化成B
      size = limit.toString();
      size = size.substring(0, size.indexOf(".") + 3) + "  B";
    } else if (limit < 0.1 * 1024 * 1024) {
      //小于0.1MB，则转化成KB
      size = (limit / 1024).toString();
      size = size.substring(0, size.indexOf(".") + 3) + "  KB";
    } else if (limit < 0.1 * 1024 * 1024 * 1024) {
      //小于0.1GB，则转化成MB
      size = (limit / (1024 * 1024)).toString();
      print(size.indexOf("."));
      size = size.substring(0, size.indexOf(".") + 3) + "  MB";
    } else {
      //其他转化成GB
      size = (limit / (1024 * 1024 * 1024)).toString();
      size = size.substring(0, size.indexOf(".") + 3) + "  GB";
    }
    return size;
  }

  Widget _buildName() {
    return Container(
      margin: const EdgeInsets.only(top: 24, bottom: 12, left: 15, right: 15),
      child: TextField(
        controller: _userNameEditController,
        onChanged: (value) {
          setState(() {
            // checkLoginText();
          });
        },
        style: TextStyle(height: 1.5),
        cursorColor: Colors.redAccent,
        enableSuggestions: false,
        autocorrect: false,
        maxLength: 300,
        maxLines: 15,
        minLines: 10,
        decoration: InputDecoration(
          hintText: "请输入抖音链接",
          filled: true,
          fillColor: Colors.white,
          contentPadding:
              const EdgeInsets.symmetric(vertical: 10, horizontal: 16),
          enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(20),
              borderSide: BorderSide(color: Colors.white, width: 2.0)),
          focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(20),
            borderSide: BorderSide(
              color: Colors.white,
              width: 2,
            ),
          ),
        ),
      ),
    );
  }
}
